<template>
  <q-dialog v-model="pop" persistent>
    <q-card class="bg-grey-3" style="width: 800px; max-width: 80vw;">
      <q-card-section>
        <div class="text-h6">{{title}}</div>
      </q-card-section>

      <q-card-section class="q-pa-none bg-white">
        <canvas id="signCanvas" />
      </q-card-section>
      <slot>
      </slot>

      <q-card-actions align="right">
        <q-btn label="取消" color="grey" v-close-popup @click="cancel" />
        <q-space />
        <q-btn label='清空' color="secondary" @click="handleReset" />
        <q-btn label="确定" color="primary" @click="handleGenerate" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script>
// import SmoothSignature from 'smooth-signature';
let SmoothSignature = null;
import('smooth-signature').then(result => {
  SmoothSignature = result.default;
});

export default {
  props: {
    uid: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      pop: false,
      title: '',

      signature: null, // 签名画面
      options: {
        width: 800, // 实际渲染的宽度(px)
        height: 300, // 实际渲染的高度(px)
        scale: 2, // 画布缩放，可用于提高清晰度
        openSmooth: true, // 是否开启笔锋
        minWidth: 4, // 画笔最小宽度(px)，开启笔锋时画笔最小宽度
        maxWidth: 10, // 画笔最大宽度(px)，开启笔锋时画笔最大宽度，或未开启笔锋时画笔正常宽度
        color: '#000000', // 画笔颜色
        bgColor: '' // 画布背景颜色，默认透明
      },

      token: '',
      promiseResult: null
    }
  },
  mounted () {
  },
  methods: {
    show (title, token) {
      this.title = title || '手写签名';
      if (token) this.token = token;

      this.pop = true;

      // 取签名
      this.$nextTick(() => {
        const canvas = document.querySelector('#signCanvas');
        this.signature = new SmoothSignature(canvas, this.options);

        this.getSign(); // 根据uid取上一次签名
      });
      return new Promise((resolve, reject) => {
        this.promiseResult = { resolve, reject };
      });
    },
    dataURLtoFile (dataURI) { // 将base64转换为blob
      // 去掉url的头，并转换为byte
      const split = dataURI.split(',');
      const bytes = window.atob(split[1]);
      // 处理异常,将ascii码小于0的转换为大于0
      const ab = new ArrayBuffer(bytes.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], { type: split[0] });
    },
    uploadImages (data) { // 上传图片
      const self = this;

      const signImg = this.dataURLtoFile(data);
      const formdata = new FormData();
      formdata.append('sign.png', signImg);

      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: this.$q.localStorage.getItem('token'),
          clientauth: this.$q.localStorage.getItem('clientToken')
        }
      };
      if (this.token) {
        config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            customizeAuth: this.token
          }
        };
      }

      return new Promise(resolve => {
        self.$axios.post('/upload', formdata, config).then(({ data }) => {
          resolve(data);
        }).catch(err => {
          console.log(err);
        });
      });
    },
    handleReset () { // 清屏
      this.signature.clear();
    },
    handleGenerate () { // 确定签名
      if (this.signature.isEmpty()) {
        this.$q.notify({
          message: '没有签名请重签',
          color: 'negative',
          icon: 'error',
          position: 'center',
          timeout: 2000
        });
        return;
      }

      this.saveSign(); // 保留签名下次用

      // 上传签名图片
      const signURI = this.signature.toDataURL();
      this.uploadImages(signURI).then(data => {
        const ret = data.images.map(v => {
          return {
            image: v.url,
            size: v.size,
            thumb: v.thumb,
            filename: v.filename
          }
        });
        this.promiseResult.resolve(ret);
        this.$emit('submit', ret);
        this.pop = false;
      });
    },
    getSign () {
      return new Promise(resolve => {
        if (this.uid) {
          this.$axios.post('/c/system/getSign', { id: this.uid }).then(({ data }) => {
            if (data.result === 'ok') { // 取到签名，画到签名板上
              const img = new Image();
              img.src = data.sign;

              const signCanvas = document.querySelector('#signCanvas');
              const myCanvas = signCanvas.getContext('2d');
              img.onload = () => {
                myCanvas.drawImage(img, 0, 0, parseFloat(window.getComputedStyle(signCanvas).width), parseFloat(window.getComputedStyle(signCanvas).height));
                resolve('');
              };
            } else {
              resolve('');
            }
          });
        } else {
          resolve('');
        }
      });
    },
    saveSign () {
      if (this.uid) {
        const sign = this.signature.toDataURL();
        this.$axios.post('/c/system/saveSign', { id: this.uid, sign });
      }
    },
    cancel () {
      this.promiseResult.resolve(null);
      this.$emit('submit', null);
      this.pop = false;
    }
  }
}
</script>
